package bg.cinema_system.service;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import bg.cinema_system.DAO.MailDao;
import bg.cinema_system.DAO.UserDAO;
import bg.cinema_system.pojo.Mail;
import bg.cinema_system.utils.SendMail;



public class MailService {
	
	
	public void sendEmailTo(int userId, String movieName, Date movieStartTime, List<Integer> reservedSeats) throws SQLException{
		String email = UserDAO.getUserMail(userId);
		Mail mail = MailDao.getMailByType("RESERVE");
		SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm");
		mail.setBody(populateMailBody(mail.getBody(), movieName, sdf.format(movieStartTime), reservedSeats));
		SendMail sm = new SendMail();
		sm.sendEmailTo(email, mail.getBody(), mail.getSubject());
	}
	
	private String populateMailBody(String mailBody, String movieName, String movieStartTime, List<Integer> reservedSeats){
		List<String> change = Arrays.asList("%name%", "%date%", "%seat%");
		StringBuilder sb = new  StringBuilder(mailBody);
		int name = sb.indexOf(change.get(0));
		if(name >0){
			sb.replace(name, name+6, movieName);
		}
		int date = sb.indexOf(change.get(1));
		if(date > 0){
			sb.replace(date, date+6, movieStartTime);
		}
		int seat = sb.indexOf(change.get(2));
		if(seat > 0){
			sb.replace(seat, seat+6, reservedSeats.toString());
		}
		return sb.toString();
	}
	
}
